import React, { useState, useEffect, useRef } from "react";
import "../../css/zh/MiCarousel.css"; // 样式文件

interface MiCarouselProps {
  images: string[];
  interval?: number;
}

const MiCarousel: React.FC<MiCarouselProps> = ({ images, interval = 3000 }) => {
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  const [isHovered, setIsHovered] = useState<boolean>(false);
  const timerRef = useRef<number | null>(null);

  // 自动轮播逻辑
  useEffect(() => {
    if (!isHovered) {
      timerRef.current = setInterval(() => {
        goToNext();
      }, interval);
    }
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [currentIndex, isHovered, interval]);

  const goToPrev = (): void => {
    setCurrentIndex((prev) => (prev === 0 ? images.length - 1 : prev - 1));
  };

  const goToNext = (): void => {
    setCurrentIndex((prev) => (prev === images.length - 1 ? 0 : prev + 1));
  };

  const goToSlide = (index: number): void => {
    setCurrentIndex(index);
  };

  return (
    <div
      className="mi-carousel"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* 轮播图片 */}
      <div className="carousel-slides">
        {images.map((image, index) => (
          <div
            key={index}
            className={`carousel-slide ${
              index === currentIndex ? "active" : ""
            }`}
            style={{ backgroundImage: `url(${image})` }}
          />
        ))}
      </div>

      {/* 左右导航按钮 */}
      <button className="carousel-button prev" onClick={goToPrev}>
        <span className="iconfont">&#xe601;</span>
      </button>
      <button className="carousel-button next" onClick={goToNext}>
        <span className="iconfont">&#xe601;</span>
      </button>

      {/* 指示点 */}
      <div className="carousel-dots">
        {images.map((_, index) => (
          <button
            key={index}
            className={`carousel-dot ${index === currentIndex ? "active" : ""}`}
            onClick={() => goToSlide(index)}
          />
        ))}
      </div>
    </div>
  );
};

export default MiCarousel;
